import 'whatwg-fetch';
import {Base64} from 'js-base64';
import md5 from 'md5';

// 将对象拼接成 key1=val1&key2=val2&key3=val3 的字符串形式
function obj2params(obj) {
  let result = '';
  for (let item in obj)
    result += '&' + item + '=' + encodeURIComponent(obj[item]);

  if (result)
    result = result.slice(1);

  return result;
}

// 发送 post 请求
export function postWithoutToken(url, paramsObj) {
  let result = fetch(url, {
    method: 'POST',
    headers: {
      'Accept': 'application/json, text/plain, */*',
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: obj2params(paramsObj)
  });

  return result;
}

// 发送 post 请求
export function postWithoutTokenBody(url, paramsObj) {
  let result = fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(paramsObj)
  });

  return result;
}

// 发送 post 请求
export function post(url, paramsObj, token) {
  let result = fetch(url, {
    method: 'POST',
    headers: {
      'Accept': 'application/json, text/plain, */*',
      'Content-Type': 'application/x-www-form-urlencoded',
      'X-Auth-Token': 'Bearer ' + token
    },
    body: obj2params(paramsObj)
  });

  return result;
}

// 发送 post 请求
export function postMultipart(url, file, token) {
  let formData = new FormData();
  //file is actually new FileReader.readAsDataURL(myId.files[0]);
  formData.append('file', file);

  let result = fetch(url, {
    method: 'POST',
    headers: {
      'X-Auth-Token': 'Bearer ' + token
    },
    body: formData
  });

  return result;
}

export function postBody(url, paramsObj, token, randomKey) {

  let bodyObj;
  console.log('paramsObj:',paramsObj);
  if (process.env.NODE_ENV === "dev" || process.env.NODE_ENV === "fDev" || process.env.API_ENV === "test") {
    bodyObj = paramsObj;
  } else {
    const baseBody = Base64.encode(JSON.stringify(paramsObj));
    bodyObj = {
      object: baseBody,
      sign: md5(baseBody + randomKey)
    }
  }


  const result = fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Auth-Token': 'Bearer ' + token
    },
    body: JSON.stringify(bodyObj)
  });
  return result;
}
